package com.tools.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tools.common.enums.ResultCode;
import com.tools.common.result.Result;
import com.tools.mapper.user.UserRoleMapper;
import com.tools.pojo.user.po.UserRole;
import com.tools.service.user.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> addUserRole(Long userId, Long roleId) {
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        boolean result = save(userRole);
        if (!result) {
            return Result.fail(ResultCode.DATA_ADD_ERROR);
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> removeUserRole(Long id) {
        boolean result = removeById(id);
        if (!result) {
            return Result.fail(ResultCode.DATA_DEL_ERROR);
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> batchRemoveUserRole(List<Long> ids) {
        boolean result = removeByIds(ids);
        if (!result) {
            return Result.fail(ResultCode.DATA_DEL_ERROR);
        }
        return Result.success();
    }

    @Override
    public Result<List<Long>> getUserRoles(Long userId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        List<UserRole> userRoles = baseMapper.selectList(queryWrapper);
        List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return Result.success(roleIds);
    }

    @Override
    public Result<List<Long>> getRoleUsers(Long roleId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getRoleId, roleId);
        List<UserRole> userRoles = baseMapper.selectList(queryWrapper);
        List<Long> userIds = userRoles.stream().map(UserRole::getUserId).collect(Collectors.toList());
        return Result.success(userIds);
    }
}
